package com.iot08.admin.service;

import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.admin.utils.buckettool.BaseBucketTool;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.Advert;
import com.iot08.common.response.Response;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.UUIDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Description: 广告业务逻辑
 * @time: 2020/10/22 11:40
 * @author: Rock
 */
@Service
public class AdvertService extends BaseService<Advert> {

    @Resource
    private UserService userService;
    @Resource
    private OperationService operationService;
    @Resource
    private BaseBucketTool baseBucketTool;



    /**
     * @param [page, type, role, ip, startTime, endTime, user]
     * @time: 2020/9/14 16:06
     * @author: Rock
     * @version 1.0
     */
    public Page<Advert> list(PageVO page, Integer type, Integer status, SysUser user) {
        PageableImpl pageable = new PageableImpl();
        page.setSort(Sort.by(Sort.Order.desc("create_time")));
        pageable.setPage(page);

        Criteria criteria = new Criteria();
        criteria.and("deleted").is(0);
        if (StringUtils.isNotEmpty(page.getSearchValue())) {
            criteria.and("title").regex(".*?" + page.getSearchValue() + ".*?", "i");
        }
        if (type != null) {
            criteria.and("type").is(type);
        }
//        else {
//            criteria.and("type").gt(0);
//        }
        if (status != null) {
            criteria.and("status").is(status);
        }

        Query query = new Query().addCriteria(criteria);
        long count = this.count(query);
        page.setTotalResult((int) count);
        List<Advert> list = this.find(query.with(pageable));
        for (Advert advert : list) {
            advert.setCreatorUser(userService.findById(advert.getCreator()));
            advert.setPublisherUser(userService.findById(advert.getPublisher()));
        }
        Page<Advert> result = new PageImpl<Advert>(list, pageable, count);
        return result;
    }

    /**
     * 添加广告
     *
     * @param advert
     * @param imgUrlFile
     * @param includeQRcodeImageFile
     * @param bottomBtnImageFile
     * @time: 2020/10/22 18:26
     * @author: Rock
     * @version 1.0
     */
    public void add(Advert advert, MultipartFile imgUrlFile, MultipartFile includeQRcodeImageFile,
                    MultipartFile bottomBtnImageFile, SysUser user, String ip) throws IOException {
        if (advert != null) {
            if (imgUrlFile != null && !imgUrlFile.isEmpty()) {
                String suffix = imgUrlFile.getOriginalFilename().substring(imgUrlFile.getOriginalFilename().lastIndexOf("."));
                String imgUrl = BaseBucketTool.ADVERT_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
                baseBucketTool.upload(imgUrl, imgUrlFile, 1);
                advert.setImgUrl(baseBucketTool.getDOMAIN() + imgUrl);
            }
            if (includeQRcodeImageFile != null && !includeQRcodeImageFile.isEmpty()) {
                String suffix = includeQRcodeImageFile.getOriginalFilename().substring(includeQRcodeImageFile.getOriginalFilename().lastIndexOf("."));
                String includeQRcodeImage = BaseBucketTool.ADVERT_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
                baseBucketTool.upload(includeQRcodeImage, includeQRcodeImageFile, 1);
                advert.setIncludeQRcodeImage(baseBucketTool.getDOMAIN() + includeQRcodeImage);
            }
            if (bottomBtnImageFile != null && !bottomBtnImageFile.isEmpty()) {
                String suffix = bottomBtnImageFile.getOriginalFilename().substring(bottomBtnImageFile.getOriginalFilename().lastIndexOf("."));
                String bottomBtnImage = BaseBucketTool.ADVERT_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
                baseBucketTool.upload(bottomBtnImage, bottomBtnImageFile, 1);
                advert.setBottomBtnImage(baseBucketTool.getDOMAIN() + bottomBtnImage);
            }

            if (StringUtil.isBlank(advert.getId())) {
                advert.setId(UUIDGenerator.generate());
            }
            if (StringUtil.isBlank(advert.getStatus())) {
                advert.setStatus(0);
            }
            advert.setDeleted(0);
            advert.setCreateTime(new Date());
            this.save(advert);
            if (new Integer(-1).equals(advert.getType())) {
                operationService.add(user, ip, "插屏媒体位", "添加",
                        String.format("添加插屏媒体位: %s ", advert.getTitle()));
            } else if (new Integer(-2).equals(advert.getType())) {
                operationService.add(user, ip, "悬浮媒体位", "添加",
                        String.format("添加悬浮媒体位: %s ", advert.getTitle()));
            } else {
                operationService.add(user, ip, "媒体位管理", "添加",
                        String.format("添加媒体位: %s ", advert.getTitle()));
            }
        }
    }

    /**
     * @param advert
     * @param imgUrlFile
     * @param includeQRcodeImageFile
     * @param bottomBtnImageFile
     * @time: 2020/10/22 22:40
     * @author: Rock
     * @version 1.0
     */
    public void update(Advert advert, MultipartFile imgUrlFile, MultipartFile includeQRcodeImageFile,
                       MultipartFile bottomBtnImageFile, SysUser user, String ip) throws IOException {
        Update update = new Update();
        if (imgUrlFile != null && !imgUrlFile.isEmpty()) {
            String suffix = imgUrlFile.getOriginalFilename().substring(imgUrlFile.getOriginalFilename().lastIndexOf("."));
            String imgUrl = BaseBucketTool.ADVERT_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
            baseBucketTool.upload(imgUrl, imgUrlFile, 1);
            update.set("img_url", baseBucketTool.getDOMAIN() + imgUrl);
        }
        if (includeQRcodeImageFile != null && !includeQRcodeImageFile.isEmpty()) {
            String suffix = includeQRcodeImageFile.getOriginalFilename().substring(includeQRcodeImageFile.getOriginalFilename().lastIndexOf("."));
            String includeQRcodeImage = BaseBucketTool.ADVERT_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
            baseBucketTool.upload(includeQRcodeImage, includeQRcodeImageFile, 1);
            update.set("include_QRcode_image", baseBucketTool.getDOMAIN() + includeQRcodeImage);
        }
        if (bottomBtnImageFile != null && !bottomBtnImageFile.isEmpty()) {
            String suffix = bottomBtnImageFile.getOriginalFilename().substring(bottomBtnImageFile.getOriginalFilename().lastIndexOf("."));
            String bottomBtnImage = BaseBucketTool.ADVERT_COMPLAINT_PATH + UUIDGenerator.generate() + suffix;
            baseBucketTool.upload(bottomBtnImage, bottomBtnImageFile, 1);
            update.set("bottom_btn_image", baseBucketTool.getDOMAIN() + bottomBtnImage);
        }
        update.set("title", advert.getTitle());
        update.set("link", advert.getLink());
        update.set("type", advert.getType());
        update.set("skip_type", advert.getSkipType());
        update.set("update_time", new Date());
        if (StringUtil.isNotBlank(advert.getIndex())) {
            update.set("index", advert.getIndex());
        }
        if (StringUtil.isNotBlank(advert.getSmallProgramId())) {
            update.set("small_program_id", advert.getSmallProgramId());
            update.set("small_program_path", advert.getSmallProgramPath());
        }
        if (StringUtil.isNotBlank(advert.getJumpTipsWords())) {
            update.set("jump_tips_words", advert.getJumpTipsWords());
        }
        if (StringUtil.isNotBlank(advert.getAdvertFirm())) {
            update.set("advert_firm", advert.getAdvertFirm());
        }
        if (StringUtil.isNotBlank(advert.getNumber())) {
            update.set("number", advert.getNumber());
        }
        if (StringUtil.isNotBlank(advert.getStatus())) {
            update.set("status", advert.getStatus());
        }
        //可显APP
        update.set("show_app_type", advert.getShowAppType());
        this.updateById(advert.getId(), update);
        if (new Integer(-1).equals(advert.getType())) {
            operationService.add(user, ip, "插屏媒体位", "编辑",
                    String.format("编辑插屏媒体位: %s ", advert.getTitle()));
        } else if (new Integer(-2).equals(advert.getType())) {
            operationService.add(user, ip, "悬浮媒体位", "编辑",
                    String.format("编辑悬浮媒体位: %s ", advert.getTitle()));
        } else {
            operationService.add(user, ip, "媒体位管理", "编辑",
                    String.format("编辑媒体位: %s ", advert.getTitle()));
        }
    }

    /**
     * @param id
     * @param status
     * @param userId
     * @time: 2020/10/22 22:52
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> updateStatus(String id, Integer status, SysUser user, String ip) {
        Advert advert = this.findById(id);
        if (advert != null && status != null) {
            Update update = new Update();
            update.set("status", status);
            if (status == 0) {
                //撤销发布
                update.set("unpublisher", user.getId());
                update.set("unpublish_time", new Date());
                update.set("update_time", new Date());
                this.updateById(id, update);
                if (new Integer(-1).equals(advert.getType())) {
                    operationService.add(user, ip, "插屏媒体位", "撤销",
                            String.format("撤销插屏媒体位: %s ", advert.getTitle()));
                } else if (new Integer(-2).equals(advert.getType())) {
                    operationService.add(user, ip, "悬浮媒体位", "撤销",
                            String.format("撤销悬浮媒体位: %s ", advert.getTitle()));
                } else {
                    operationService.add(user, ip, "媒体位管理", "撤销",
                            String.format("撤销媒体位: %s ", advert.getTitle()));
                }
                return Response.successResponse();
            } else if (status == 1) {
                //发布
                update.set("publisher", user.getId());
                update.set("publish_time", new Date());
                update.set("update_time", new Date());
                this.updateById(id, update);
                if (new Integer(-1).equals(advert.getType())) {
                    operationService.add(user, ip, "插屏媒体位", "发布",
                            String.format("发布插屏媒体位: %s ", advert.getTitle()));
                } else if (new Integer(-2).equals(advert.getType())) {
                    operationService.add(user, ip, "悬浮媒体位", "发布",
                            String.format("发布悬浮媒体位: %s ", advert.getTitle()));
                } else {
                    operationService.add(user, ip, "媒体位管理", "发布",
                            String.format("发布媒体位: %s ", advert.getTitle()));
                }
                return Response.successResponse();
            } else {
                return Response.failedResponse();
            }
        }
        return Response.failedResponse();
    }

    /**
     * @param id
     * @param user
     * @param ip
     * @time: 2020/10/23 9:32
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> updateDel(String id, SysUser user, String ip) {
        Advert advert = this.findById(id);
        if (advert != null) {
            Update update = new Update();
            update.set("deleted", 1);
            update.set("update_time", new Date());
            this.updateById(id, update);
            operationService.add(user, ip, "媒体位管理", "删除",
                    String.format("删除媒体位: %s ", advert.getTitle()));
            return Response.successResponse();
        }
        return Response.failedResponse();
    }

    /**
     * @param type
     * @time: 2020/10/23 14:51
     * @author: Rock
     * @version 1.0
     */
    public Advert getByType(Integer type) {
        return this.findOne(new Query(Criteria.where("type").is(type)));
    }

}
